package logger

import (
	"fmt"
	"github.com/spf13/pflag"
)

type Config struct {
	LogFile          string `json:"logFile" yaml:"logFile"`
	LogFileMaxSizeMB int    `json:"logFileMaxSizeMB" yaml:"logFileMaxSizeMB"`
	ToConsole        bool   `json:"toConsole" yaml:"toConsole"`
	LogLevel         string `json:"logLevel" yaml:"logLevel"`
	LogFormat        string `json:"logFormat" yaml:"logFormat"`
	MaxBackups       int    `json:"maxBackups" yaml:"maxBackups"`
	MaxAge           int    `json:"maxAge" yaml:"maxAge"`
	Compress         bool   `json:"compress" yaml:"compress"`
}

func DefaultLogOptions() *Config {
	return &Config{
		ToConsole:        true,      // 开启标准错误输出
		LogFile:          "",        // 日志文件路径
		LogFileMaxSizeMB: 100,       // 日志切割大小
		LogLevel:         "info",    // 日志级别
		LogFormat:        "console", // 控制台或文件输出
		MaxAge:           30,
		MaxBackups:       5,
		Compress:         false,
	}
}

func (s *Config) Validate() []error {
	if s == nil {
		return nil
	}

	var allErrors []error

	switch s.LogLevel {
	case "debug", "info", "warn", "error":
	default:
		allErrors = append(allErrors, fmt.Errorf("--log-level must be one of debug,info,warn,error"))
	}

	switch s.LogFormat {
	case "json", "console":
	default:
		allErrors = append(allErrors, fmt.Errorf("--log-encode-type must be one of json or console"))
	}

	return allErrors
}

func (s *Config) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&s.LogFile, "log-file", s.LogFile, "File path to write log to.")

	fs.IntVar(&s.LogFileMaxSizeMB, "log-file-max-size", s.LogFileMaxSizeMB, "Maximum size a log file can grow, threshold to split file.")

	fs.BoolVar(&s.ToConsole, "log-to-console", s.ToConsole, "Log to standard console instead of file.")

	fs.StringVar(&s.LogLevel, "log-level", s.LogLevel, "Default log level: debug, info, warn, error")

	fs.StringVar(&s.LogFormat, "log-format", s.LogFormat, "Log struct: console or json")

	fs.IntVar(&s.MaxBackups, "log-max-backups", s.MaxBackups, "Maximum number of old log files to retain. Default retain all")

	fs.IntVar(&s.MaxAge, "log-max-age", s.MaxAge, "MaxAge is the maximum number of days to retain old log files based on the  timestamp encoded in their filename.")

	fs.BoolVar(&s.Compress, "log-compress", s.Compress, "Compress determines if the rotated log files should be compressed using gzip.")
}
